package com.elh.serurity.utils;
import cn.hutool.core.annotation.Alias;
import cn.hutool.core.util.TypeUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.lang3.reflect.TypeUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liulei
 **/
public class BeanUtil  {


    public static void copyProperties(Object source, Object target) throws Exception {
        if((source instanceof Map) && (target instanceof Map)){
            ((Map) source).putAll((Map) target);
        }
        List<Field> targetFieldList = new ArrayList<>();
        ReflectionUtils.doWithFields(target.getClass(),field -> targetFieldList.add(field),ReflectionUtils.COPYABLE_FIELDS);
        for (Field targetField : targetFieldList) {
            String value = null;
            if(targetField.isAnnotationPresent(Alias.class)){
                value = targetField.getAnnotation(Alias.class).value();
                value = StringUtils.isBlank(value) ? targetField.getName() : value;

            }else{
                value = targetField.getName();
            }
            Field sourceField = FieldUtils.getField(source.getClass(), value,true);
            if(sourceField == null){
                continue;
            }
            ReflectionUtils.setField(sourceField,source,targetField.get(target));
        }
    }







}
